<script>
import { rooms, getDormitoryList } from '@/api/v2/dorm'
import { atLeastN, get } from '@/utils/kris_utils'

import DeleteRoom from './components/DeleteRoom'
import CreateRoom from './components/CreateRoom'
import EditRoom from './components/EditRoom'
export default {
  components: {
    DeleteRoom,
    CreateRoom,
    EditRoom
  },
  data() {
    return {
      rooms: [],
      pagination: {
        size: 10,
        current: 1,
        total: 0
      },
      loadingStatuses: {
        loading: false
      },

      createRoomDialog: {
        visible: false
      },

      editRoomDialog: {
        visible: false,
        room: null
      },
      selectedRows: [],
      isDeleting: false,
      form: {},
      apartments: []
    }
  },
  computed: {
    roomsFormatted() {
      return this.rooms.map((item) => {
        const {
          id,
          name,
          number,
          rent,
          remark,
          user_company_count,
          dormitory,
          created_at,
          userCompany,
          photo
        } = item

        const capacity = number
        const used = user_company_count
        const remain = capacity - used
        const employees = userCompany?.map((employee) => {
          const { company_id, id: recordId, user } = employee
          return {
            companyId: company_id,
            recordId,
            user
          }
        })
        return {
          id,
          name,
          apartment: dormitory,
          bad: number,
          rent: parseFloat(rent),
          remark,
          capacity,
          used,
          remain,
          createdAt: created_at,
          employees,
          photos: JSON.parse(photo)
        }
      })
    },

    isActionDisabled() {
      return false
    }
  },
  created() {
    this.initData()
  },
  mounted() {
    console.log(this.rooms)
  },
  methods: {
    atLeastN,
    showCreateRoomDialog() {
      this.createRoomDialog.visible = true
    },
    showEditRoomDialog() {
      this.createRoomDialog.visible = true
    },
    handleEditRoom(room) {
      console.log(room,'room');
      const { apartment, name, bad, rent,remark, employees, photos, id } = room
      console.log(remark,'remark');
      this.editRoomDialog.room = {
        apartmentID: apartment.id,
        id,
        roomName: name,
        bad,
        rent,
        remark,
        employees,
        photos
      }
      this.editRoomDialog.visible = true
    },

    // 创建结果事件回调
    handleCreateSuccess(result) {
      this.$message.success(result.message ?? '创建成功')
      this.createRoomDialog.visible = false
      this.refreshTable()
    },
    handleCreateFailed(e) {
      this.$message.error(e.message ?? '创建失败')
    },

    // 修改事件结果
    handleUpdateSuccess(result) {
      this.$message.success(result.message ?? '修改成功')
      this.editRoomDialog.visible = false
      this.refreshTable()
    },
    handleUpdateFailed(e) {
      this.$message.error(e.message ?? '修改失败')
    },

    // 分页
    handlePageChange(currentPage) {
      this.pagination.current = currentPage
      this.refreshTable()
    },
    handlePageSizeChange(size) {
      this.pagination.size = size
      this.refreshTable()
    },

    sleep(t) {
      return new Promise((r) => setTimeout(r, t))
    },
    toEmployeeProfile(employee) {
      this.$router.push({
        path: `/personnel-files/show/${employee.id}`,
        query: { tag_title: employee?.username + '-查看', show: true }
      })
    },

    async getRooms() {
      const { size, current } = this.pagination

      const { name, dormitory_id, minrent, maxrent, username, number } =
        this.form

      const params = {
        paginate: size,
        page: current,
        name: name,
        dormitory_id: dormitory_id,
        minrent: minrent,
        maxrent: maxrent,
        username: username,
        number: number
      }
      const result = await rooms(params)
      this.rooms = result?.data ?? []
      this.pagination.total = result?.meta?.total ?? 0
    },
    async refreshTable() {
      try {
        if (this.loadingStatuses.loading) return
        this.loadingStatuses.loading = true
        await this.sleep(400)
        await this.loadData()
        this.loadingStatuses.loading = false
      } catch (e) {
        this.loadingStatuses.loading = false
      } finally {
        this.loadingStatuses.loading = false
      }
    },
    async loadData() {
      const result = await Promise.allSettled([this.getRooms()])

      const failTasks = result.filter((item) => item.status === 'rejected')
      if (failTasks.length <= 0) return
      throw failTasks.at(0)
    },

    async getDorm() {
      const result = await getDormitoryList()
      this.apartments = result.data.map(item => {
        return {
          id: item.id,
          label: item.address
        }
      })
    },
    async initData() {
      try {
        this.loadingStatuses.loading = true
        await this.loadData()
        await this.getDorm()
        this.loadingStatuses.loading = false
      } catch (e) {
        this.loadingStatuses.loading = false
      }
    },
    onSubmit() {
      this.getRooms()
    },
    selectCompanyChange(data) {
      console.log(data)
    },
    handleDetails(row) {
      console.log(row, '---------')
      this.$router.push({
        path: `/dormitory/room/details/${row.id}`
      })
    }
  }
}
</script>

<template>
  <div class="app-container room-container">
    <CreateRoom
      v-model="createRoomDialog.visible"
      @success="handleCreateSuccess"
      @failed="handleCreateFailed"
    />

    <EditRoom
      v-model="editRoomDialog.visible"
      :room="editRoomDialog.room"
      @success="handleUpdateSuccess"
      @failed="handleUpdateFailed"
    />

    <el-card style="margin-bottom: 20px;border: none;" shadow="never">
      <el-form :inline="true" :model="form" class="demo-form-inline">
        <el-form-item label="房间名">
          <el-input v-model="form.name" placeholder="请输入房间名" />
        </el-form-item>
        <el-form-item label="所属宿舍">
          <el-select v-model="form.dormitory_id" clearable placeholder="请选择宿舍地址" @change="(data) => selectCompanyChange(data)">
            <el-option v-for="item in apartments" :key="item.id" :label="item.label" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="租金范围">
          <div style="display: flex">
            <el-input
              v-model="form.minrent"
              placeholder="请输入租金最小值"
            />
            <span class="lineae">至</span>
            <el-input
              v-model="form.maxrent"
              placeholder="请输入租金最大值"
            />
          </div>
        </el-form-item>
        <el-form-item label="居住人员">
          <el-input
            v-model="form.username"
            placeholder="请输入居住人员名字"
          />
        </el-form-item>
        <el-form-item label="可住人数">
          <el-input v-model="form.number" placeholder="请输入可住人数" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">查询</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card style="border: none;" shadow="never">
      <el-row :gutter="40" justify="center">
        <el-col :span="24">
          <div class="header-container">
            <el-button
              class="header-container__item"
              type="primary"
              icon="el-icon-plus"
              @click="showCreateRoomDialog"
            >
              创建房间
            </el-button>

            <el-button
              class="header-container__item"
              icon="el-icon-refresh-right"
              :disabled="loadingStatuses.loading"
              @click="refreshTable"
            >
              刷新
            </el-button>
          </div>
        </el-col>
      </el-row>
      <el-row :gutter="40">
        <el-col :span="24">
          <el-table
            v-loading="loadingStatuses.loading"
            :data="roomsFormatted"
            row-key="id"
            style="width: 100%"
            border
          >
            <el-table-column
              prop="apartment.address"
              label="所属宿舍"
              align="center"
            />
            <el-table-column prop="name" label="房间名称" align="center" />
            <el-table-column label="可住/已住" align="center">
              <template slot-scope="scope">
                {{ scope.row.capacity }} / {{ scope.row.used }}
                <el-popover trigger="click" placement="top" title="房间概览">
                  <div class="room-overview">
                    <span
                      v-for="(employee, employeeIndex) in scope.row.employees"
                      :key="employeeIndex"
                      class="wrapper"
                    >
                      <el-tag
                        size="small"
                        type="info"
                        plain
                        @click="toEmployeeProfile(employee.user)"
                      >
                        {{ employee?.user?.username }}
                      </el-tag>
                    </span>
                    <span
                      v-for="i in scope.row.remain"
                      :key="i.id"
                      class="wrapper"
                    >
                      <el-tag size="small" type="success" plain>空位</el-tag>
                    </span>
                  </div>
                  <el-button slot="reference" type="text">
                    <i class="el-icon-view" />
                  </el-button>
                </el-popover>
              </template>
            </el-table-column>
            <el-table-column prop="rent" label="租金" align="center" />
            <el-table-column label="照片" align="center" width="400px">
              <template slot-scope="scope">
                <el-image
                  v-if="atLeastN(scope.row.photos, 1)"
                  style="width: 40px; height: 40px"
                  :src="scope.row.photos.length > 0 ? scope.row.photos[0] : []"
                  :preview-src-list="scope.row.photos"
                  fit="contain"
                />
                <el-tag v-else size="small" type="warning">未上传</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="createdAt" label="创建时间" align="center" />

            <el-table-column prop="actions" label="操作" align="center">
              <template slot-scope="scope">
                <div class="actions">
                  <el-button
                    circle
                    plain
                    type="primary"
                    icon="el-icon-edit"
                    @click="handleEditRoom(scope.row)"
                  />
                  <DeleteRoom :room-id="scope.row.id" @success="refreshTable" />
                  <el-button
                    type="success"
                    circle
                    plain
                    @click="handleDetails(scope.row)"
                  ><svg-icon icon-class="seeDetails" /></el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>

      <el-row :gutter="40">
        <el-col :span="24">
          <el-pagination
            style="padding-bottom: 0;"
            class="block"
            layout="total, sizes, prev, pager, next, jumper"
            :current-page="pagination.current"
            :page-sizes="[10, 50, 100]"
            :page-size="pagination.size"
            :total="pagination.total"
            :disabled="loadingStatuses.loading"
            @size-change="handlePageSizeChange"
            @current-change="handlePageChange"
          />
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>

<style lang="scss">
.room-container {
  .header-container {
    padding-bottom: 20px;

    &__item {
      margin-right: 10px;
    }
  }

  .el-pagination {
    padding: 16px 0;

    .btn-prev,
    .btn-next {
      margin: 0;
      margin-right: 6px;
    }
  }

  .actions {
    .el-button {
      margin: 5px;
    }
  }
}

.room-overview {
  max-width: 500px;

  .wrapper {
    padding: 2px;
    display: inline-block;
    .el-tag {
      cursor: pointer;
    }
  }
}
.content {
  display: flex;
  margin-bottom: 20px;
  .sift {
    margin-right: 40px;
    display: flex;
  }
  .search {
    width: 200px;
  }

  .name {
    width: 70px;
    margin-right: 10px;
    display: flex;
    justify-content: center;
    align-items: center;
  }
}
.lineae {
  display: flex;
  justify-content: center;
  align-items: center;
  margin: 0 10px;
}
.block{
  display: flex;
  justify-content: center;
}
</style>
